package com.sheng.sign.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SessionFactory;

import com.sheng.sign.entity.Course;
import com.sheng.sign.entity.User;

public class UserDaoImpl implements UserDao{
    private SessionFactory sessionFactory;
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	
	public boolean register(User user) {
		try {
			user.setIsDelete(0);
			sessionFactory.getCurrentSession().save(user);
			System.out.println("==来到了DaoImpl=="+user);
			return true;
		} catch (HibernateException e) {
			return false;
		}
	}
	public User login(User user) {
		User u = null;
		u = (User)sessionFactory.getCurrentSession().createQuery("from User where username=:username and password=:password")
		.setString("username", user.getUsername())
		.setString("password", user.getPassword()).uniqueResult();
		return u;
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<User> findAllList() {
		String hql = "from User where 1=1 and is_delete=0";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);  
        List list = query.list();  
        return list;
	}
	@Override
	public User findById(User user) {
		System.out.println("来到了findById:"+user.getId());
		Query query = sessionFactory.getCurrentSession().createQuery("from User where id='"+user.getId()+"'");
		List list = query.list();  
		if (null != list && 0 < list.size()) {
			user = (User) list.get(0);
		}
		System.out.println("==findById查询后=="+user.getId()+";"+user.getUsername()+";"+user.getPassword());
		return user;
	}
	@Override
	public boolean edit(User user) {
		try {
			user.setIsDelete(0);
			sessionFactory.getCurrentSession().update(user);
			System.out.println("==来到了DaoImpl=="+user);
			return true;
		} catch (HibernateException e) {
			return false;
		}
	}
	@Override
	public boolean delete(User user) {
		try {
			user.setIsDelete(1);
			sessionFactory.getCurrentSession().update(user);
			System.out.println("==来到了DaoImpl=="+user);
			return true;
		} catch (HibernateException e) {
			return false;
		}
	}
	@Override
	public List<User> findByUserId(User user) {
		String hql = "from User where  user_id='"+user.getUserId()+"' and is_delete=0 ";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);  
        List list = query.list();  
        return list;
	}

}
